/*
 * @Author: nqx2007 fenglimima334@163.com
 * @Date: 2023-12-04 18:00:36
 * @LastEditors: nqx2007 fenglimima334@163.com
 * @LastEditTime: 2023-12-12 18:10:18
 * @FilePath: /operator-manager/src/app.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
// 运行时配置
import RightContent from '@/components/RightContent';
import { getRemoteMenu, getUserInfo } from '@/services';
import { whiteRoutes,DEFAULT_NAME } from '@/utils/globalConstants';
import { AppstoreOutlined } from '@ant-design/icons';
import type { MenuDataItem } from '@ant-design/pro-components';
import { ProBreadcrumb } from '@ant-design/pro-components';
import type { RunTimeLayoutConfig } from '@umijs/max';
import { history } from '@umijs/max';
import { errorConfig } from '../config/requestErrorConfig';
import { PermissionType } from './access';
import { loginPath, tenantType } from './utils/globalConstants';
// 图标的映射，可以根据需求添加更多的，如果返回的菜单没有icon字段，也可以根据name值写一个映射表
const IconMap = {
  AppstoreOutlined: <AppstoreOutlined />,
};
// 每个菜单项目都添加上对应的图标
const loopMenuItem = (menus: any[]): MenuDataItem[] => {
  return menus.map(({ icon, childrenList, ...item }) => {
    const children = childrenList?.filter(
      (item: Record<string, any>) => item?.type === PermissionType.MENU,
    );
    return {
      ...item,
      icon: icon && IconMap[icon as 'AppstoreOutlined'],
      children: children && loopMenuItem(children),
    };
  });
};
//获取登录的用户信息
const fetchUserInfo = async () => {
  try {
    const response = await getUserInfo({
      skipErrorHandler: true,
    });
    console.log('初始状态获取用户信息1111', response?.data);
    //接口返回的数据太乱，需要处理一下
    const { sysUserInfoVo = {}, menuList = [] } = response?.data ?? {};
    const permissions = menuList.map((item: any) => ({
      access: item?.access,
      type: item?.type,
    }));
    return { ...sysUserInfoVo, permissions };
  } catch (error) {
    history.push(loginPath);
    return undefined;
  }
};

//全局的初始状态
export async function getInitialState(): Promise<{
  currentUser?: Record<string, any>;
  fetchUserInfo?: () => Promise<Record<string, any> | undefined>;
}> {
  //如果不是登录页面，执行
  const { location } = history;
  if (location.pathname !== loginPath) {
    const currentUser = await fetchUserInfo();
    return { currentUser, fetchUserInfo };
  }
  return { fetchUserInfo };
}

//运行时的布局配置
export const layout: RunTimeLayoutConfig = ({
  initialState,
  setInitialState,
}) => {
  return {
    layout: 'mix',
    logo: 'https://img.alicdn.com/tfs/TB1YHEpwUT1gK0jSZFhXXaAtVXa-28-27.svg',
    title: DEFAULT_NAME,
    menu: {
      locale: false,
      // 每当 initialState?.currentUser?.id 发生修改时重新执行request获取菜单
      params: {
        account: initialState?.currentUser?.id,
      },
      request: async () => {
        if (!initialState?.currentUser?.id) {
          return [];
        }
        const menus = await getRemoteMenu();
        console.log('从接口获取的菜单',menus)
        return loopMenuItem(menus);
      },
    },
    onPageChange: async (location) => {
      if (!initialState?.currentUser) {
        const currentUser = await fetchUserInfo();
        console.log('页面切换获取用户信息2222', initialState, currentUser);
        setInitialState({ ...initialState, currentUser });
        if (!currentUser && !whiteRoutes.includes(location?.pathname as string)) {
          return history.push(loginPath);
        }
      }
    },
    headerTitleRender: (logo) => {
      return (
        <div
          style={{
            display: 'flex',
            alignContent: 'flex-start',
            alignItems: 'center',
            width: '256px',
          }}
        >
          <span>{logo}</span>
          <span
            style={{
              lineHeight: '18px',
              fontSize: '14px',
              paddingLeft: '10px',
            }}
          >
            {DEFAULT_NAME}
          </span>
        </div>
      );
    },
    headerContentRender: () => {
      return <ProBreadcrumb />;
    },
    rightContentRender: () => <RightContent />,
    breadcrumbProps: {
      itemRender: (item) => {
        return <span>{item.title}</span>;
      },
    },
  };
};
//请求配置
export const request = {
  ...errorConfig,
  requestInterceptors: [
    (url: string, options: Record<string, any>) => {
      // 登录成功之后会将接口返回的token存储到localStorage中，然后每次请求的时候取出来放在请求头部
      const token = localStorage.getItem('token');
      if (options?.method?.toLowerCase() === 'get') {
        //get方法加参数需要加在params中
        return {
          url,
          options: {
            ...options,
            headers: {
              ...(options?.headers ?? {}),
              ticket: token,
            },
            params: {
              ...(options?.params ?? {}),
              tenantId: tenantType, //因为后端把小二后台和商家管理后台的接口都合在一起了，所以需要前端加上tenantId来做区分
            },
          },
        };
      } else {
        return {
          url,
          options: {
            ...options,
            headers: {
              ...(options?.headers ?? {}),
              ticket: token,
            },
            data: {
              ...(options?.data ?? {}),
              tenantId: tenantType, //因为后端把小二后台和商家管理后台的接口都合在一起了，所以需要前端加上tenantId来做区分
            },
          },
        };
      }
    },
  ],
};
